package com.siyoumi.app.modules.iot.service;

import com.siyoumi.app.entity.IotProduct;
import com.siyoumi.app.modules.iot.vo.VaIotProduct;
import com.siyoumi.app.service.IotProductService;
import com.siyoumi.component.XApp;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.service.IWebService;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

//产品
@Slf4j
@Service
public class SvcIotProduct
        implements IWebService {
    static public SvcIotProduct getBean() {
        return XSpringContext.getBean(SvcIotProduct.class);
    }

    static public IotProductService getApp() {
        return IotProductService.getBean();
    }

    public JoinWrapperPlus<IotProduct> listQuery() {
        return listQuery(InputData.getIns());
    }

    /**
     * select
     *
     * @return query
     */
    public JoinWrapperPlus<IotProduct> listQuery(InputData inputData) {
        String name = inputData.input("name");
        String type = inputData.input("type");

        JoinWrapperPlus<IotProduct> query = getApp().join();
        query.eq("ipro_x_id", XHttpContext.getX())
                .eq("ipro_del", 0);
        getApp().addQueryAcc(query);

        if (XStr.hasAnyText(name)) { //名称
            query.like("ipro_name", name);
        }

        return query;
    }

    public XReturn edit(InputData inputData, VaIotProduct vo) {
        List<String> ignoreField = new ArrayList<>();
        if (inputData.isAdminEdit()) {
            ignoreField.add(getApp().fdAccId());
            vo.setIpro_type(null);
            vo.setIpro_key(null);
        } else {
            vo.setIpro_id(XApp.getStrID("P"));
            vo.setIpro_key(XApp.shortId());
        }

        return XApp.getTransaction().execute(status -> {
            XReturn r = getApp().saveEntity(inputData, vo, false, ignoreField);

            return r;
        });
    }

    /**
     * 删除
     */
    @SneakyThrows
    @Transactional(propagation = Propagation.MANDATORY)
    public XReturn delete(List<String> ids) {
        XReturn r = XReturn.getR(0);
        getApp().delete(ids);

        return r;
    }
}
